/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2022-12-07 09:31:42
 * @LastEditors: huangtianyang
 * @LastEditTime: 2024-02-21 17:35:45
 * @FilePath: \cxl-admin\src\pages\system\protocol\edit\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { editProtocl, getVersionByCode, protocolList } from '@/apis/system/protocol'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'

/**
 * 定义渠道常量
 */
export enum channelEnum {
    H5 = 1,
    Ios,
    PC,
    Android
}

/**
 * 定义渠道列表
 */
export const channelOptions = [
    { label: 'H5', name: 'channel' },
    { label: 'Ios', name: 'channel' },
    { label: 'PC', name: 'channel' },
    { label: 'Android', name: 'channel' }
]

export class ProtocolEditData {
    /**
     * 定义协议内容字段
     */
    protocol = reactive({
        code: '',
        channel: [],
        version: ''
    })

    /**
     * 定义协议表单验证规则
     */
    rules = {
        code: [{ required: true, message: '请选择协议', trigger: 'change' }],
        channel: [{ required: true, message: '请选择应用渠道', trigger: 'change' }],
        version: [{ required: true, message: '请选择协议号', trigger: 'change' }]
    }

    /**
     * 协议下拉列表
     */
    options = reactive(protocolList)

    /**
     * 协议内容
     */
    protocolContent = ref('')

    /**
     * 监听选择的协议
     * @param val
     */
    onSelectProtocol = (val: any) => {
        this.protocol.code = val
        this.getVersion(val)
    }

    /**
     * 监听用户输入的协议内容
     */
    result = ''
    onContentUpdate = (res: string) => {
        this.result = res
    }

    /**
     * 查询选中协议的版本号
     * @param code
     */
    getVersion = (code: string) => {
        getVersionByCode(code).then(res => {
            this.protocol.version = res.data.data
        })
    }

    /**
     * 提交
     */
    onSubmit(callback = () => {}) {
        const arr: any[] = []
        if (this.protocol.channel.length) {
            this.protocol.channel.forEach((item: string) => {
                arr.push(channelEnum[item as keyof typeof channelEnum])
            })
        }
        let name = ''
        this.options.forEach(item => {
            if (item.value == this.protocol.code) {
                name = item.label
            }
        })

        if (this.result === '') {
            ElMessage.error('协议内容不能为空！')
            return
        }
        editProtocl({
            code: this.protocol.code,
            content: this.result,
            name: name,
            type: arr.join(','),
            version: this.protocol.version
        }).then((res: any) => {
            console.log(res)
            if (res.data.value === 200) {
                ElMessage.success('新增协议成功！')
                callback()
            }
        })
    }
}
